package com.insigma.business.qrcode.job.consumer.impl;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import com.insigma.business.qrcode.common.converter.CompanyProviderConverter;
import com.insigma.business.qrcode.common.converter.JobRecruitPositionProviderConverter;
import com.insigma.business.qrcode.common.dto.BaseApiGetRequest;
import com.insigma.business.qrcode.common.template.BasePagingResponse;
import com.insigma.business.qrcode.common.template.area.BaseProviderImpl;
import com.insigma.business.qrcode.common.template.area.ScenarioCodeEnum;
import com.insigma.business.qrcode.common.template.area.ServiceCallback;
import com.insigma.business.qrcode.common.util.AdminAreaCodeUtils;
import com.insigma.business.qrcode.common.util.BizCheckUtil;
import com.insigma.business.qrcode.common.util.ResponseUtils;
import com.insigma.business.qrcode.common.vo.BaseResponse;
import com.insigma.business.qrcode.intell.dto.UserDTO;
import com.insigma.business.qrcode.intell.entity.UserDO;
import com.insigma.business.qrcode.intell.service.UserService;
import com.insigma.business.qrcode.common.converter.UserProviderConverter;
import com.insigma.business.qrcode.job.dto.JobCheckStatusEnum;
import com.insigma.business.qrcode.job.dto.PositionStatusEnum;
import com.insigma.business.qrcode.job.dto.request.JobRecruitPositionInsertRequest;
import com.insigma.business.qrcode.job.entity.JobCandidatePositionEnrollDO;
import com.insigma.business.qrcode.job.entity.JobFavoriteDO;
import com.insigma.business.qrcode.job.service.JobCandidatePositionEnrollService;
import com.insigma.business.qrcode.job.service.JobFavoriteService;
import com.insigma.business.qrcode.soldier.dto.CompanyDTO;
import com.insigma.business.qrcode.job.dto.search.JobRecruitPositionBSearcher;
import com.insigma.business.qrcode.soldier.dto.JobRecruitPositionDTO;
import com.insigma.business.qrcode.soldier.entity.CompanyDO;
import com.insigma.business.qrcode.soldier.entity.JobFairParticipateDO;
import com.insigma.business.qrcode.soldier.entity.JobRecruitPositionDO;
import com.insigma.business.qrcode.soldier.service.CompanyService;
import com.insigma.business.qrcode.soldier.service.JobFairParticipateService;
import com.insigma.business.qrcode.soldier.service.JobRecruitPositionService;
import com.insigma.business.qrcode.job.consumer.CandidateResumeConsumer;
import com.insigma.business.qrcode.job.dto.ExpectedInfoRequest;
import com.insigma.business.qrcode.job.dto.JobCandidateResumeDTO;
import com.insigma.business.qrcode.job.dto.search.JobFavoriteBSearcher;
import com.insigma.business.qrcode.job.dto.request.JobRecruitPositionSearchRequest;
import com.insigma.business.qrcode.job.consumer.JobRecruitPositionConsumer;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class JobRecruitPositionConsumerImpl extends BaseProviderImpl implements JobRecruitPositionConsumer {
    @Autowired
    private CandidateResumeConsumer candidateResumeConsumer;

    @Autowired
    private JobRecruitPositionService jobRecruitPositionService;

    @Autowired
    private JobFavoriteService jobFavoriteService;

    @Autowired
    private JobCandidatePositionEnrollService jobCandidatePositionEnrollService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private JobFairParticipateService jobFairParticipateService;

    @Autowired
    private UserService userService;

    @Override
    public BasePagingResponse<List<JobRecruitPositionDTO>> searchJobRecruitPosition(JobRecruitPositionSearchRequest searchRequest) {

        final BasePagingResponse<List<JobRecruitPositionDTO>> basePagingResponse = new BasePagingResponse<>();
        serviceTemplate.execute(basePagingResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(searchRequest, "查询分页JobRecruitPosition的请求参数不能为空");
            }

            @Override
            public void executeService() {
                if (Strings.isBlank(searchRequest.getSortKeyValueJoint())) {
                    searchRequest.setSortKeyValueJoint("createDatetime_desc");
                }

                final JobRecruitPositionBSearcher jobRecruitPositionBSearcher = JobRecruitPositionProviderConverter.convertRequestSO2Searcher(searchRequest);

                if (Strings.isNotBlank(searchRequest.getSearchType())) {
                    if ("RECOMMEND".equals(searchRequest.getSearchType())) {
                        if (Strings.isNotBlank(searchRequest.getSoldierId())) {
                            List<String> list = extractExpect(searchRequest.getSoldierId());
                            if (CollectionUtils.isNotEmpty(list)) {
                                jobRecruitPositionBSearcher.setOrderTypeCodes(list);
                            }
                        }
                    }
                }

                if (StringUtils.isNotBlank(searchRequest.getAreaCode())) {
                    jobRecruitPositionBSearcher.setAreaCode(AdminAreaCodeUtils.getCutdAreaCode(searchRequest.getAreaCode()));
                }

                final List<JobRecruitPositionDO> jobRecruitPositionDOList = jobRecruitPositionService.search(jobRecruitPositionBSearcher);
                final List<JobRecruitPositionDTO> jobRecruitPositionDTOList = JobRecruitPositionProviderConverter.convertResponseDOList2DTOList(jobRecruitPositionDOList);
                ResponseUtils.buildSuccessPagingResponse(basePagingResponse, jobRecruitPositionDTOList, searchRequest, jobRecruitPositionBSearcher.getTotalCount());
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.JOB_RECRUIT_POSITION_SEARCH;
            }
        });

        return basePagingResponse;
    }

    @Override
    public BaseResponse<JobRecruitPositionDTO> getJobRecruitPosition(BaseApiGetRequest request) {
        final BaseResponse<JobRecruitPositionDTO> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(request, "获取单条JobRecruitPosition的请求参数不能为空");
                BizCheckUtil.checkNotBlank((String) request.getId(), "id不能为空");
            }

            @Override
            public void executeService() {
                final JobRecruitPositionDO jobRecruitPositionDO = jobRecruitPositionService.get((String) request.getId());
                BizCheckUtil.checkNotNull(jobRecruitPositionDO, "不存在");

                final JobRecruitPositionDTO remoteObj = JobRecruitPositionProviderConverter.convertResponseDO2DTO(jobRecruitPositionDO);

                if (Strings.isNotBlank(request.getSoldierId())) {

                    JobFavoriteBSearcher favoriteBSearcher = new JobFavoriteBSearcher(0, 10);
                    favoriteBSearcher.setSoldierId(request.getSoldierId());
                    favoriteBSearcher.setFavoriteHostId(request.getId());
                    List<JobFavoriteDO> search = jobFavoriteService.search(favoriteBSearcher);
                    if (CollectionUtils.isNotEmpty(search)) {
                        remoteObj.setFavorite(Boolean.TRUE);
                    }


                    JobCandidatePositionEnrollDO position = jobCandidatePositionEnrollService.getBySoldierIdAndPositionId(request.getSoldierId(), remoteObj.getId());
                    if (position != null) {
                        remoteObj.setDelivery(Boolean.TRUE);
                    }
                }

                CompanyDO companyDO = companyService.get(jobRecruitPositionDO.getOrgId());
                if (companyDO == null) {
                    JobFairParticipateDO jobFairParticipateDO = jobFairParticipateService.getByOrgId(jobRecruitPositionDO.getOrgId());
                    if (jobFairParticipateDO != null) {
                        companyDO = CompanyProviderConverter.convertJobFairParticipateDO2CompanyDO(jobFairParticipateDO);
                        companyDO.setLegalAddress(companyDO.getLegalAddress());
                        companyDO.setRemark(companyDO.getDescription());
                    }
                }

                if (companyDO != null) {
                    CompanyDTO companyDTO = CompanyProviderConverter.convertResponseDO2DTO(companyDO);
                    remoteObj.setCompany(companyDTO);


                    UserDO userDO = userService.get(companyDO.getManagerId());
                    if (userDO != null) {
                        final UserDTO userDTO = UserProviderConverter.convertResponseDO2DTO(userDO);
                        userDTO.setPassword(null);
                        remoteObj.setUser(userDTO);
                    }
                }

                ResponseUtils.setupSuccessResponse(baseResponse, remoteObj);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.JOB_RECRUIT_POSITION_GET;
            }
        });
        return baseResponse;
    }

    @Override
    public BaseResponse<Integer> countPositionApply(String positionId) {
        Integer integer = jobCandidatePositionEnrollService.countByPosition(positionId);
        return ResponseUtils.buildSuccessResponse(integer);
    }

    @Override
    public BaseResponse<String> insertJobReportRecruitPosition(JobRecruitPositionInsertRequest insertRequest) {
        final BaseResponse<String> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(insertRequest, "新增JobRecruitPosition的请求参数不能为空");
            }

            @Override
            public void executeService() {
                final JobRecruitPositionDO jobRecruitPositionDO = JobRecruitPositionProviderConverter.convertRequestIO2DO(insertRequest);
                jobRecruitPositionDO.setStatus(PositionStatusEnum.IN_PROGRESS.name());
                if (jobRecruitPositionDO.getWorkCity() != null && !jobRecruitPositionDO.getWorkCity().startsWith("3301")) {
                    jobRecruitPositionDO.setWorkCity("330100000000");
                }
                if (jobRecruitPositionDO.getAuditStatus() == null) {
                    jobRecruitPositionDO.setAuditStatus(JobCheckStatusEnum.SUCCESS.name());
                }
                if (jobRecruitPositionDO.getPublished() == null) {
                    jobRecruitPositionDO.setPublished(true);
                }
                jobRecruitPositionService.insert(jobRecruitPositionDO);
                ResponseUtils.setupSuccessResponse(baseResponse, jobRecruitPositionDO.getId());
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.JOB_REPORT_RECRUIT_POSITION_INSERT;
            }
        });
        return baseResponse;


    }


    private List<String> extractExpect(String soldierId) {
        JobCandidateResumeDTO resumeDTO = candidateResumeConsumer.getMyResume(soldierId).getDto();
        if (resumeDTO != null) {
            String expectedInfo = resumeDTO.getExpectedInfo();
            if (Strings.isNotBlank(expectedInfo)) {
                List<String> result = Lists.newArrayList();
                List<ExpectedInfoRequest> expectedInfoRequests = JSONArray.parseArray(expectedInfo, ExpectedInfoRequest.class);
                for (ExpectedInfoRequest expectedInfoRequest : expectedInfoRequests) {
                    String expectedPositionTypeIds = expectedInfoRequest.getExpectedPositionTypeId();
                    if (Strings.isNotBlank(expectedPositionTypeIds)) {
                        if (expectedPositionTypeIds.contains("[")) {
                            List<String> expectPositionTypeIds = JSONArray.parseArray(expectedPositionTypeIds, String.class);
                            if (CollectionUtils.isNotEmpty(expectPositionTypeIds)) {
                                result.addAll(expectPositionTypeIds);
                            }
                        } else {
                            result.add(expectedPositionTypeIds);
                        }

                    }
                }
                return result;
            }
        }
        return null;
    }
}
